﻿<!--
天地图定位工具
surfsky.github.com
2022-07
-->

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>天地图定位拾取-SURFSKY-2021</title>
    <meta name="about" content="https://blog.csdn.net/surfsky/article/details/106951716#comments_17805322"/>
    <style>
        body, html, #map {
            width: 100%;
            height: 100%;
            overflow: hidden;
            margin: 0;
            padding: 0;
        }
        .fixTop {
            position:fixed; 
            top:0px;    
            left:50%; 
            transform: translateX(-50%);
        }

        .fixBottom {
            position: fixed;
            bottom: 8px;
            left: 50%;
            transform: translateX(-50%);
            padding: 2px 5px;
            background-clip: border-box;
            border-width: 0;
            border-radius: 4px;
            color: yellow;
            text-shadow: -1px 1px 0 #000, 1px 1px 0 #000, 1px -1px 0 #000, -1px -1px 0 #000;
            font-size: 12px;
            font-family: Arial;
            word-wrap: break-word;
            display: block;
            opacity: 0.9;
            z-index:9999;
        }

        /* fixPanel */
        .fixPanel {
            display: block;
            position: fixed;
            opacity: 0.9;
            z-index: 999;
            width: 1rem;
            height: 1rem;
            border-width: 0;
            border-radius: 1rem;

            flex: 1 1 auto;
            flex-direction: column;

            background-color: #fff;
            color: #0288d1;
            font-family: Arial;
            word-wrap: normal;
        }

        .locator{
            bottom: 3rem;
            right: 1rem;
            padding: 0.3rem 0.5rem 0.5rem 0.3rem;
            cursor: pointer;
        }

        .clipboard {
            bottom: 1rem;
            right: 1rem;
            padding: 0.3rem 0.5rem 0.5rem 0.3rem;
            cursor: pointer;
        }

        .zoomInfo {
            border-style: solid;
            border-color: rgb(42, 65, 194);
            border-width: 1px;
            border-radius: 4px;
            width: 0.65rem;
            height: 0.65rem;
            top: 14rem;
            left: 1.6rem;
            padding: 0.2rem 0.2rem 0.2rem 0.15rem;
            font-size: 11px !important;
            text-align:center;
        }

        /* CARD */
        .card {
            display: flex;
            flex: 1 1 auto;
            -ms-flex: 1 1 auto;
            flex-direction: column;
            /*width: 600px;*/
            /*height: 24px;*/
            position: fixed;
            top: 8px;
            left: 50%;
            transform: translateX(-50%);
            padding: 2px 5px;
            background-color: #ffffff;
            background-clip: border-box;
            border-width: 0;
            border-radius: 4px;
            font-size: 12px;
            font-family: Arial;
            word-wrap: break-word;
            color: #f5f6f7;
            display: block;
            opacity: 0.9;
            z-index:9999;
        }

        #tbAddr {
            width: 200px;
            border-radius: 4px;
            border-color: #808080;
            border-width: 0px;
            padding: 2px 5px 2px 5px;
            background-color: gray;
            color: white;
            outline: none;
        }
        #tbPos {
            width: 200px;
            border-radius: 4px;
            border-color: #808080;
            border-width: 0px;
            padding: 2px 5px 2px 5px;
            background-color: gray;
            color: white;
            outline: none;
        }
    </style>
    <script src="https://api.tianditu.gov.cn/api?v=3.0&tk=2c71689b0e3d5d72314d4bfe1102d5c0"></script>
    <script src="contents/clipboard.min.js"></script>
    <script src="contents/toast.js"></script>

    <script src="https://webapi.amap.com/maps?v=1.4.15&key=8f1b4bfa36143143452768fafbf3b8bd&plugin=AMap.Scale,AMap.OverView,AMap.ToolBar,AMap.Geocoder,AMap.MapType"></script>
    <script src="https://api.map.baidu.com/api?v=2.0&ak=A60cece53af65e45e359f578c9e70d32"></script>
    <script src="https://map.qq.com/api/js?v=2.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>
</head>
<body>
    <div id="map"></div>
    <div class="fixPanel zoomInfo">
        <div id="zoomLevel">18</div>
    </div>
    <!--
    <div class="fixPanel clipboard" id="btnClip">
        <img src="contents/clippy.svg" width="20" height="20" alt="Copy to clipboard">
    </div>
    <div class="fixPanel locator" onclick="locate()">
        <img src="contents/locator.svg" width="20" height="20" alt="Move to current location">
    </div>
    -->
    <div class="card">
        <input id="tbAddr" type="text" value="温州新田园" class="textbox" />
        <button onclick="searchTianditu()">天地图</button>
        <button onclick="searchGaode()">高德</button>
        <button onclick="searchBaidu()">百度</button>
        <button onclick="searchTencent()">腾讯</button>
        <br/>
        <input id="tbPos" type="text" value="120.56591, 27.56139" class="textbox" />
        <button onclick="gotoPos()">移动</button>
        <button onclick="locate()">当前</button>
        <button id="btnClip">拷贝</button>
    </div>
    <div class="fixBottom">更多定制版本请联系微信 surfsky</div>
</body>
</html>


<script>
//----------------------------------------------
// 地图
//----------------------------------------------
// map
var map = new TMap("map");
var center = new TLngLat(116.39141, 39.92348);
var zoom = 12;
var isShowAddr = false;

// locator
map.centerAndZoom(center, zoom);
locate();
map.enableDrag();
map.enableHandleMouseScroll();
map.enableDoubleClickZoom();

// control
map.setMapType(TMAP_HYBRID_MAP);
map.addControl(new TNavigationControl({
    type: "TMAP_NAVIGATION_CONTROL_LARGE",
    anchor: "TMAP_ANCHOR_TOP_LEFT",
    offset: [0, 0],
    showZoomInfo: true
}));
map.addControl(new TScaleControl());
map.addControl(new TMapTypeControl());

// marker & label
var marker = new TMarker(center);
marker.enableDragging();
map.addOverLay(marker);
var label = new TLabel({ offset: new TPixel(15, -20) });
map.addOverLay(label);
setMarkerAndLabel();


//----------------------------------------------
// 地图事件
//----------------------------------------------
// map events
TEvent.addListener(map, "mousedown", function () { isShowAddr = true; });
TEvent.addListener(map, "mouseup", function () { isShowAddr = false; });
TEvent.addListener(map, "move", function (lnglat) { setMarkerAndLabel(); });
TEvent.addListener(map, "moveend", function (lnglat) {
    setMarkerAndLabel();
    // 逆地址解析
    if (isShowAddr){
        var geocode = new TGeocoder();
        geocode.getLocation(lnglat, function (result) {
            if (result.getStatus() == 0) {
                var addr = result.getAddress();
                showAddr(addr);
            }
        });
    }
});


//----------------------------------------------
// 剪贴板
//----------------------------------------------
// copy to clipboard
var clipboard = new ClipboardJS('#btnClip', {
    text: function () { return label.getLabel(); }
});
clipboard.on('success', function (e) {
    toast("已复制到剪贴板: " + e.text, 1000);
});
clipboard.on('error', function (e) {
    alert(e);
});


//----------------------------------------------
// 双指缩放控制
//----------------------------------------------
/*
// 阻止safari浏览器双击放大功能
let lastTouchEnd = 0  //更新手指弹起的时间
document.documentElement.addEventListener("touchstart", function (event) {
    //多根手指同时按下屏幕，禁止默认行为
    if (event.touches.length > 1) {
        event.preventDefault();
    }
});
document.documentElement.addEventListener("touchend", function (event) {
    let now = (new Date()).getTime();
    if (now - lastTouchEnd <= 300) {
        //当两次手指弹起的时间小于300毫秒，认为双击屏幕行为
        event.preventDefault();
    }else{ // 否则重新手指弹起的时间
        lastTouchEnd = now;
    }
}, false);
*/
// 阻止双指放大页面
document.documentElement.addEventListener("gesturestart", function (event) {
    event.preventDefault();
});


//----------------------------------------------
// 辅助方法
//----------------------------------------------
// locate to current position
function locate(){
    navigator.geolocation.getCurrentPosition(function (position) {
        var zoom = map.getZoom();
        var lng = position.coords.longitude;
        var lat = position.coords.latitude;
        map.panTo(new TLngLat(lng, lat), zoom);
    });
}

// set marker, label position and text
function setMarkerAndLabel() {
    var zoom = map.getZoom();
    var zoomLabel = document.getElementById("zoomLevel");
    zoomLabel.innerText = zoom;

    var lnglat = map.getCenter();
    marker.setLngLat(lnglat);
    label.setLabel(getText(lnglat) + " ｜ " + getDFMText(lnglat));
    label.setLngLat(lnglat);
    showLngLat(lnglat.getLng(), lnglat.getLat());
}

// lnglat text
function getText(lnglat) {
    return lnglat.getLng() + ", " + lnglat.getLat();
}

// 获取度分秒文本
function getDFMText(lnglat){
    var lng = lnglat.getLng();
    var lat = lnglat.getLat();
    var lngText = (lng > 0)
        ? "E " + changeToDFM(lng)
        : "W " + changeToDFM(-lng)
        ;
    var latText = (lat > 0)
        ? "N " + changeToDFM(lat)
        : "S " + changeToDFM(-lat)
        ;
    return lngText + ", " + latText;
}

// 经纬度转化为度分秒
// 1度=60分，1分=60秒
// 如113.125°就是，113度，0.125x60=7.5分，取整分就是7，0.5x60=30秒
function changeToDFM(du) {
   du = du.toString();
   const arr1 = du.split(".");
   const d = arr1[0];
   let tp = "0." + arr1[1]
   tp = String(tp * 60); //进行强制类型转换
   const arr2 = tp.split(".");
   const f = arr2[0];
   tp = "0." + arr2[1];
   tp = tp * 60;
   const m = tp.toFixed(2);//保留两位小数
   const dfm = d + "°" + f + "'" + m + "\"";
   return dfm;
}


// 显示经度纬度
function showLngLat(lng, lat) {
    var tb = document.getElementById("tbPos");
    tb.value = lng + ", " + lat;
}

// 显示文本地址
function showAddr(addr) {
    var tb = document.getElementById("tbAddr");
    tb.value = addr;
}

// 将地图中心移到指定位置
function goto(lng, lat) {
    var lnglat = new TLngLat(lng, lat);
    map.panTo(lnglat);
    setMarkerAndLabel();
}
function gotoPos(){
    var pos = document.getElementById("tbPos").value;
    var n = pos.indexOf(',');
    if (n != -1){
        var lng = pos.substr(0, n);
        var lat = pos.substr(n+1);
        goto(lng, lat);
    }
}

//----------------------------------------------
// 查找
//----------------------------------------------
// 搜索地址（天地图）
function searchTianditu() {
    var addr = document.getElementById("tbAddr").value;
    var search = new TLocalSearch(map, {
        pageCapacity: 1,
        onSearchComplete: function (result) {
            var ps = result.getPois();
            if (ps.length > 0) {
                var lnglat = ps[0].lonlat;
                var n = lnglat.indexOf(' ');
                if (n != -1) {
                    var lng = lnglat.substr(0, n);
                    var lat = lnglat.substr(n + 1, lnglat.length - 1);
                    goto(lng, lat);
                }
            }else{
                toast("找不到：" + addr, 1000);
            }
        }
    });
    search.search(addr, 1);
}

// 搜索地址（高德）
function searchGaode() {
    var addr = document.getElementById("tbAddr").value;
    AMap.plugin('AMap.Geocoder', function () {
        var geocoder = new AMap.Geocoder();
        geocoder.getLocation(addr, function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
                var p = result.geocodes[0].location;
                var lng = p.getLng();
                var lat = p.getLat();
                goto(lng, lat);
            }else{
                toast("找不到：" + addr, 1000);
            }
        })
    })
}

// 搜索地址（百度）
function searchBaidu() {
    var addr = document.getElementById("tbAddr").value;
    var myGeo = new BMap.Geocoder();
    myGeo.getPoint(addr, function (p) {
        if (p) {
            var lng = p.lng;
            var lat = p.lat;
            goto(lng, lat);
        } else {
            toast("找不到：" + addr, 1000);
        }
    }, "");
}

// 搜索地址（腾讯）
function searchTencent() {
    var addr = tbAddr.value;
    var geocoder = new qq.maps.Geocoder({
        complete: function (result) {
            var p = result.detail.location;
            if (p) {
                var lng = p.lng;
                var lat = p.lat;
                goto(lng, lat);
            } else {
                toast("找不到：" + addr, 1000);
            }
        }
    });
    geocoder.getLocation(addr);
}

</script>
